package com.stnet.service.enterprice.chinamobile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import com.modules.util.MD5Util;
import com.stnet.bases.ReadProperties;
import com.stnet.front.enterprice.Product;
import com.stnet.web.front.OnlineRechargeAction;

/**
 * @author Messcat
 * @version 1.1
 * 
 */
public class ProductManagerDaoImpl implements ProductManagerDao {
	
	// private String path =
	// Thread.currentThread().getContextClassLoader().getResource("").getPath();
	private String path;
	private String filename = "xmlfiles/respont.xml";
	
	public List<Product> findProducts(int type) {
		path = this.getPath();
		List<Product> productList = new ArrayList<Product>();
		DocumentBuilderFactory buf = DocumentBuilderFactory.newInstance(); // xm解析器生成工具
		DocumentBuilder db;
		Product product = null;
		// 生成xml文件
		try {
			doPost(type);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		// xml2object
		try {
			db = buf.newDocumentBuilder();
			Document dom = db.parse(new File(path + filename));
			NodeList list = dom.getElementsByTagName("product");// 返回节点对象
			for (int i = 0; i < list.getLength(); i++) {
				String price = list.item(i).getAttributes().getNamedItem(
						"price").getTextContent();
				product = new Product();
				product.setId(Integer.valueOf(list.item(i).getAttributes()
						.getNamedItem("id").getTextContent()));
				product.setName(list.item(i).getAttributes().getNamedItem(
						"name").getTextContent());
				product.setInfo(list.item(i).getAttributes().getNamedItem(
						"info").getTextContent());
				product.setPrice(price.substring(0, price.length() - 2) + "."
						+ price.substring(price.length() - 2, price.length()));
				productList.add(product);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return productList;
	}

	public void doPost(int type) throws IOException {
		ReadProperties rp = new ReadProperties("onlinerecharge.properties");
		Properties p = rp.getProperties();
		String PARTNER = p.getProperty("customer.id");// 代理商id
		String KEY = p.getProperty("customer.key");
		String PRODUCT_URL = p.getProperty("producturl");
		String CHARSET = "utf-8";
		StringBuilder sb = new StringBuilder();
		StringBuilder sb2 = new StringBuilder();
		sb.append("partner=").append(PARTNER).append("&type=").append(type)
				.append("&").append(KEY);
		String sign = MD5Util.MD5(sb.toString());
		sb2.append("partner=").append(PARTNER).append("&type=").append(type)
				.append("&sign=").append(sign).append("&charset=").append(
						CHARSET);
		String param = sb2.toString();
		URL url = new URL(PRODUCT_URL);
		URLConnection connection = url.openConnection();
		connection.setDoOutput(true);
		OutputStreamWriter out = new OutputStreamWriter(connection
				.getOutputStream(), "utf-8");
		out.write(param); // post的关键所在！
		out.flush();
		out.close();

		InputStream l_urlStream;
		l_urlStream = connection.getInputStream();
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(new File(path + filename));
			byte buffer[] = new byte[1024];
			int len = 0;
			while ((len = l_urlStream.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
			}
			fos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				l_urlStream.close();
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public String getPath() {
		String path = null;
		try {
			path = getClass().getProtectionDomain().getCodeSource()
					.getLocation().getPath();
			if (path.indexOf("WEB-INF") > 0) {
				path = path.substring(0, path.indexOf("WEB-INF/classes"));
			} else {
				try {
					throw new IllegalAccessException("路径获取错误");
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
			
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		return path;
	}

}